package eu.liquify.ui {
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.net.SharedObject;
	import no.doomsday.console.ConsoleUtil;
	public class FolderInput extends PersistentUIItem {
		private var textBox:TextBox;
		private var btn:Button;
		public var folder:File;
		public var valid:Boolean;
		public function FolderInput(options:Object = null) {
			super(options);
			
			folder = new File();
			folder.addEventListener(Event.SELECT, folderSelected);
			
			var box:HBox = new HBox();
			box.addChild(textBox = new TextBox("Path", "", { w: 300 } )).addEventListener(Event.CHANGE, textChange);
			box.addChild(btn = new Button("Browse", { marginTop: 0, marginRight: 2 } )).addEventListener(MouseEvent.CLICK, browse);
			addChild(box);
			
			loadFolder();
			validateFolder();
		}
		
		private function textChange(e:Event):void {
			validateFolder();
			saveFolder();
		}
		
		private function folderSelected(e:Event):void {
			textBox.text = folder.nativePath;
			validateFolder();
			saveFolder();
		}
		
		private function loadFolder():void {
			var obj:Object = load("folder");
			textBox.text = obj ? String(obj) : "";
		}
		private function saveFolder():void {
			save("folder", textBox.text);
		}
		
		private function browse(e:MouseEvent):void {
			folder.browseForDirectory("Select a folder");
		}
		
		private function validateFolder():void {
			valid = false;
			if (textBox.text.length > 0) {
				try {
					folder.nativePath = textBox.text;
					folder.canonicalize();
					ConsoleUtil.print(folder.nativePath);
					valid = folder.exists;
				} catch (e:ArgumentError) {
					valid = false;
				}
			}
			textBox.backgroundColor = valid ? 0xA7FCA9 : 0xE9B494;
		}
	}
}